package com.test.javafaq_portal.service.impl;

import com.test.javafaq_portal.entity.Comment;
import com.test.javafaq_portal.entity.User;
import com.test.javafaq_portal.mapper.CommentMapper;
import com.test.javafaq_portal.mapper.UserMapper;
import com.test.javafaq_portal.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.javafaq_portal.service.ServiceException;
import com.test.javafaq_portal.vo.CommentVo;
import com.test.javafaq_portal.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author test.com
 * @since 2025-04-11
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    CommentMapper commentMapper;

    @Override
    public Comment upadateComment(Integer commentId, CommentVo commentVo, String username) {
        //获取当前用户信息
        User user = userMapper.findUserByUsername(username);
        //获取评论信息
        Comment comment = commentMapper.selectById(commentId);
        //只有讲师和发布者本人才能修改
        if(user.getType() != null && user.getType() == 1 || user.getId() == comment.getUserId()){
            //设置修改对象
            comment.setContent(commentVo.getContent());
            int num = commentMapper.updateById(comment);
            if(num != 1){
                throw ServiceException.busy();
            }
            return  comment;
        }
        throw ServiceException.invalidRequest("权限不足");
    }

    @Override
    public boolean removeComment(Integer commentId, String username) {
        //获取当前用户对象
        User user = userMapper.findUserByUsername(username);
        if(user.getType() != null && user.getType() == 1 ){
            int num = commentMapper.deleteById(commentId);
            return num == 1;
        }
        //如果不是老师，必须是评论者本人才能删除
        Comment comment = commentMapper.selectById(commentId);
        if(comment.getUserId() == user.getId()){
            int num = commentMapper.deleteById(commentId);
            return num == 1;
        }
        throw ServiceException.invalidRequest("权限不足！");
    }

    @Override
    @Transactional
    public Comment saveComment(CommentVo commentVo, String username) {
        User user = userMapper.findUserByUsername(username);
        Comment comment = new Comment()
                .setAnswerId(commentVo.getAnswerId())
                .setContent(commentVo.getContent())
                .setUserId(user.getId())
                .setUserNickName(user.getNickname())
                .setCreatetime(LocalDateTime.now());
        int num = commentMapper.insert(comment);
        if(num != 1){
            throw ServiceException.busy();
        }

        return comment;
    }
}
